<?php

namespace App\Http\Rpc;

use App\Libs\Commons\MyLogger;
use App\Libs\Commons\MyMessage;
use App\Services\Common\RpcService;

class IndexRpc extends BaseRpc
{
	private function server()
	{
		$server = new \Yar_Server($this);
		$server->handle();
	}

	private function client()
	{
		try {
			$param = request()->all();
			$method = $param['method'] ?? '';
			unset($param['method']);
			$result = RpcService::garage([
				'method' => $method,
				'data' => $param ?? []
			]);
			return response()->json($result);
		} catch (\Throwable $e) {
			return response()->json(['code' => $e->getCode(), 'msg' => $e->getMessage()]);
		}
	}

	private function auth()
	{
		if (empty($_SERVER['HTTP_TOKEN'])) {
			return false;
		}

		if ($_SERVER['HTTP_TOKEN'] != 'e013a057a0fe4bb9afb7096a3c5e90af') {
			return false;
		}
		return true;
	}

	public function index()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'RPC') !== false) {
			$this->server();
		} else {
			return $this->client();
		}
	}

	public function execute($param = [])
	{

		try {
			MyLogger::info('rpc.param', $param);
			if (!$this->auth()) {
				MyLogger::error('rpc.fail', ['msg' => 'rpc鉴权失败']);
				return $this->fail(MyMessage::NOAUTH);
			}

			$method = explode('.', $param['method']);
			$func = array_pop($method);
			$method[count($method) - 1] = ucfirst($method[count($method) - 1]);
			$class = implode('\\', $method);
			$class = "App\\Http\\Rpc\\" . ucfirst($class) . 'Rpc';

			// 检测类
			if (!class_exists($class)) {
				MyLogger::error('rpc.fail', ['msg' => '类不存在']);
				return $this->fail(MyMessage::SYSTEM_CTL_NOT_FOUND);
			}

			// 检测方法
			if (!method_exists($class, $func)) {
				MyLogger::error('rpc.fail', ['msg' => '方法不存在']);
				return $this->fail(MyMessage::SYSTEM_CTL_ACTION_NOT_FOUND);
			}

			$result = (new $class())->$func($param['data']);
			return $this->success($result);
		} catch (\Throwable $e) {
			MyLogger::error('rpc.fail', ['code' => $e->getCode(), 'msg' => $e->getCode()]);
			return $this->fail($e->getCode(), $e->getMessage());
		}
	}
}
